﻿using mscook.core;
using mscook.core.domain;
using mscook.core.services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace mscook.mvc.Core
{
    public class UserAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
    {

        private ILoginUserService iLoginUserService = UnityHelper.UnityToT<ILoginUserService>();
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool result = false;
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            if (!httpContext.User.Identity.IsAuthenticated)
                return false;

            string[] roles = Roles.Split(',');//设置的Roles
            string[] users = Users.Split(',');


            string currrentUserId = httpContext.User.Identity.Name;
            LoginUser loginUser = iLoginUserService.SelectLoginUserByLoginName(currrentUserId);
            if (loginUser == null || roles.Length == 0)
            {
                return false;
            }
            else
            {
                result= roles.Contains(loginUser.UserRole);
            }
            if (!result)
            {
                httpContext.Response.StatusCode = 403;
            }
            return result;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext.HttpContext.Response.StatusCode == 403)
            {
                filterContext.Result = new RedirectResult("/");
            }
        }
    }
}